//
//  NewRefreshController.swift
//  SinaBlog
//
//  Created by macs on 15/11/27.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit

private let kRefreshControllerOffset : CGFloat = -60.0


class NewRefreshController: UIRefreshControl {
    
    override init(){
        super.init()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        super.init()
        setupUI()
    }
    
    //开始旋转
    override func beginRefreshing() {
        super.beginRefreshing()
        refeshView.startAnimating()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refeshView.stopAnimating()
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // print(frame.origin.y);
        
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing {
            //旋转
            refeshView.startAnimating()
            return
        }
        
        if frame.origin.y < kRefreshControllerOffset && !refeshView.rotateTip {
            //旋转 pullView 使其向上
            refeshView.rotateTip = true
            
        } else if frame.origin.y > kRefreshControllerOffset && refeshView.rotateTip  {
            //旋转 pullView 使其向下
            refeshView.rotateTip = false
        }
        
        
    }
    
    private func setupUI() {
        tintColor = UIColor.clearColor()
        //添加控件
        addSubview(refeshView)
        //自动布局
        refeshView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(refeshView.bounds.size)
            // make.center.equalTo(self.snp_center)
            make.top.equalTo(self.snp_top)
        }
        
        //添加 kvo 监听者,设置在主线程
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
            
        }
        
    }
    
    //移除 kvo
    deinit{
        
        removeObserver(self, forKeyPath: "frame");
    }
    
    //懒加载控件
    private lazy var refeshView : RefreshView = RefreshView.refreshView()!
}

class RefreshView : UIView {
    
    //添加是否过旋转标记.初始为向下
    var rotateTip = false {
        didSet{
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadingView: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var tipIcon: UIImageView!
    
    class func refreshView () -> RefreshView?{
        
        //        let view = NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last as! RefreshView
        //
        let nib = UINib(nibName: "RefreshView", bundle: nil)
        let view = nib.instantiateWithOwner(nil, options: nil).last as! RefreshView
        
        return view
    }
    
    private func rotateTipIcon() {
        
        var angle = CGFloat(M_PI)
        
        //旋转动画的特点,顺时针优先+ 就近原则
        angle += rotateTip ? -0.000001 : 0.000001
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
        
    }
    
    private func startAnimating() {
        tipView.hidden = true
        
        let animKey = "transform.rotation"
        if loadingView.layer.animationForKey(animKey) != nil {
            //动画正在进行
            return;
        }
        
        let anim = CABasicAnimation(keyPath: animKey)
        anim.toValue = 2 * M_PI //(旋转一周)
        anim.duration = 0.5
        anim.repeatCount = MAXFLOAT
        anim.removedOnCompletion = false //动画是否在完成重后删除
        
        loadingView.layer.addAnimation(anim, forKey: animKey)
    }
    
    private func stopAnimating(){
        
        tipView.hidden = false
        
        loadingView.layer.removeAllAnimations()
    }
    
}